import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:http/http.dart' as http; 

class WebSocketRoute extends StatefulWidget {
  @override
  _WebSocketRouteState createState() => _WebSocketRouteState();
}

class _WebSocketRouteState extends State<WebSocketRoute> {
  final TextEditingController _controller = TextEditingController();
  late IOWebSocketChannel channel;
  dynamic _data;

  @override
  void initState() {
    super.initState();
    channel = IOWebSocketChannel.connect('wss://echo.websocket.events');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("WebSocket(文本/二进制/JSON回显)"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Form(
              child: TextFormField(
                controller: _controller,
                decoration: InputDecoration(labelText: '发送文本消息'),
              ),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: _sendMessage,
              child: Text('Send Text'),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: _sendJsonFromGitee,
              child: Text('Send JSON from Gitee'),
            ),
            StreamBuilder(
              stream: channel.stream,
              builder: (context, snapshot) {
                Widget content = SizedBox();
                if (snapshot.hasError) {
                  content = Text("网络不通...");
                } else if (snapshot.hasData) {
                  if (snapshot.data is String) {
                    String data = snapshot.data;
                    try {
                      dynamic decoded;
                      try {
                        decoded = json.decode(data);
                      } catch (e) {
                        decoded = json.decode(json.decode(data));
                      }
                      content = Text(const JsonEncoder.withIndent('  ').convert(decoded));
                    } catch (e) {
                      content = Text("echo: $data");
                    }
                  } else if (snapshot.data is List<int>) {
                    content = Text("收到二进制数据");
                  }
                }
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 24.0),
                  child: content,
                );
              },
            )
          ],
        ),
      ),
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      channel.sink.add(_controller.text);
    }
  }

  Future<void> _sendJsonFromGitee() async {
    final url = 'https://gitee.com/Leann_2023/ex3_chapter11_websocket/raw/main/assets/data.json';
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      // 直接发送UTF-8字符串，不要用gbk解码
      channel.sink.add(response.body);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取JSON失败: ${response.statusCode}')),
      );
    }
  }

  @override
  void dispose() {
    channel.sink.close();
    super.dispose();
  }
}